package com.situ.skymall.user.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.situ.model.CnRegionInfo;
import com.situ.service.CnRegionInfoService;
import com.situ.skymall.user.api.mapper.CnRegionInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 地区信息 Service 实现类
 */
@Service
public class CnRegionInfoServiceImpl extends ServiceImpl<CnRegionInfoMapper, CnRegionInfo> implements CnRegionInfoService {

    private CnRegionInfoMapper cnRegionInfoMapper;
    @Autowired
    public void setCnRegionInfoMapper(CnRegionInfoMapper cnRegionInfoMapper) {
        this.cnRegionInfoMapper = cnRegionInfoMapper;
    }

    @Override
    public List<CnRegionInfo> getByParentId(Integer parentId) {
        return cnRegionInfoMapper.selectByParentId(parentId);
    }

    @Override
    public List<CnRegionInfo> getBySuperiorCode(String superiorCode) {
        return cnRegionInfoMapper.selectBySuperiorCode(superiorCode);
    }

    @Override
    public List<CnRegionInfo> getByLevel(Integer level) {
        return cnRegionInfoMapper.selectByLevel(level);
    }

    /**
     * 根据代码获取地区完整信息（包括父级）
     */
    @Cacheable("full_region")
    @Override
    public String getFullInfoByCode(String code) {
        if (!StringUtils.hasText(code)) {
            return "";
        }

        // 1. 先根据code查询当前地区
        CnRegionInfo currentRegion = cnRegionInfoMapper.selectOne(
                new QueryWrapper<CnRegionInfo>().eq("CRI_CODE", code)
        );

        if (currentRegion == null) {
            return "未知地区";
        }

        // 2. 根据级别构建完整地址
        String fullName = currentRegion.getCriName();

        switch (currentRegion.getCriLevel()) {
            case 3: // 区县级：需要查询市和省
                fullName = getCityAndProvince(currentRegion) + fullName;
                break;
            case 2: // 市级：需要查询省
                fullName = getProvince(currentRegion) + fullName;
                break;
            case 1: // 省级：直接返回
            default:
                break;
        }

        return fullName;
    }

    /**
     * 获取省市信息（用于区县级）
     */

    private String getCityAndProvince(CnRegionInfo district) {
        StringBuilder result = new StringBuilder();

        // 1. 先查询市级
        CnRegionInfo city = cnRegionInfoMapper.selectOne(
                new QueryWrapper<CnRegionInfo>()
                        .eq("CRI_CODE", district.getCriSuperiorCode())
        );

        if (city != null) {
            result.append(city.getCriName());

            // 2. 再查询省级
            CnRegionInfo province = cnRegionInfoMapper.selectOne(
                    new QueryWrapper<CnRegionInfo>()
                            .eq("CRI_CODE", city.getCriSuperiorCode())
            );

            if (province != null) {
                result.insert(0, province.getCriName());
            }
        }

        return result.toString();
    }

    /**
     * 获取省级信息（用于市级）
     */
    private String getProvince(CnRegionInfo city) {
        CnRegionInfo province = cnRegionInfoMapper.selectOne(
                new QueryWrapper<CnRegionInfo>()
                        .eq("CRI_CODE", city.getCriSuperiorCode())
        );

        return province != null ? province.getCriName() : "";
    }

    @Cacheable("all_provinces")
    @Override
    public List<CnRegionInfo> getAllProvinces() {
        return cnRegionInfoMapper.selectAllProvinces();
    }

    @Cacheable(value = "cities", key = "#provinceCode")
    @Override
    public List<CnRegionInfo> getCitiesByProvince(String provinceCode) {
        return cnRegionInfoMapper.selectCitiesByProvince(provinceCode);
    }

    @Cacheable(value = "districts", key = "#cityCode")
    @Override
    public List<CnRegionInfo> getDistrictsByCity(String cityCode) {
        return cnRegionInfoMapper.selectDistrictsByCity(cityCode);
    }

    @Override
    public List<CnRegionInfo> searchByName(String name) {
        if (!StringUtils.hasText(name)) {
            return List.of();
        }
        return cnRegionInfoMapper.selectByNameLike(name);
    }

    @Override
    public List<CnRegionInfo> getRegionTree(Integer parentId) {
        // 查询所有有效的地区信息
        LambdaQueryWrapper<CnRegionInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CnRegionInfo::getCriDataState, 1)
                .orderByAsc(CnRegionInfo::getCriSort);

        List<CnRegionInfo> allRegions = baseMapper.selectList(wrapper);

        // 构建树形结构
        return makeTree(allRegions, parentId);
    }

    // 生成树形结构
    private List<CnRegionInfo> makeTree(List<CnRegionInfo> regions, Integer rootParentId) {
        // 创建缓存映射，提高查找效率
        Map<Integer, CnRegionInfo> cache = new HashMap<>();
        for (CnRegionInfo region : regions) {
            cache.put(region.getCriId(), region);
        }

        List<CnRegionInfo> roots = new ArrayList<>();

        // 遍历所有地区信息
        for (CnRegionInfo region : cache.values()) {
            // 如果是指定的根节点，则添加到根列表
            if (region.getCriParentId() == null || region.getCriParentId().equals(rootParentId)) {
                roots.add(region);
            } else {
                // 查找父级节点
                CnRegionInfo parent = cache.get(region.getCriParentId());
                if (parent != null) {
                    // 设置父子关联关系
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(region);
                }
            }
        }

        return roots;
    }





    @Override
    public CnRegionInfo getFullAddressTreeByCode(String code) {
        if (!StringUtils.hasText(code)) {
            return null;
        }

        // 1. 先查询指定代码的地区信息
        LambdaQueryWrapper<CnRegionInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CnRegionInfo::getCriCode, code)
                .eq(CnRegionInfo::getCriDataState, 0);
        CnRegionInfo region = baseMapper.selectOne(wrapper);

        if (region == null) {
            return null;
        }

        // 2. 递归构建完整的子树
        buildFullSubTree(region);

        return region;
    }

    // 递归构建完整子树
    private void buildFullSubTree(CnRegionInfo parent) {
        // 查询直接子节点
        LambdaQueryWrapper<CnRegionInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CnRegionInfo::getCriParentId, parent.getCriId())
                .eq(CnRegionInfo::getCriDataState, 1)
                .orderByAsc(CnRegionInfo::getCriSort);
        List<CnRegionInfo> children = baseMapper.selectList(wrapper);

        if (children != null && !children.isEmpty()) {
            parent.setChildren(children);

            // 递归为每个子节点构建子树
            for (CnRegionInfo child : children) {
                buildFullSubTree(child);
            }
        }
    }








    /**
     * 根据地区代码获取完整地址名称
     */
    public String getFullAddressName(String regionCode) {
        CnRegionInfo region = lambdaQuery()
                .eq(CnRegionInfo::getCriCode, regionCode)
                .one();
        
        if (region == null) {
            return "";
        }
        
        // 如果是省级，直接返回名称
        if (region.getCriLevel() == 1) {
            return region.getCriName();
        }
        
        // 递归获取父级名称
        StringBuilder fullName = new StringBuilder(region.getCriName());
        CnRegionInfo current = region;
        
        while (current.getCriParentId() != null && current.getCriParentId() > 0) {
            CnRegionInfo parent = getById(current.getCriParentId());
            if (parent != null) {
                fullName.insert(0, parent.getCriName() + " ");
                current = parent;
            } else {
                break;
            }
        }
        
        return fullName.toString();
    }
}